Connectivity Software User's Guide and Reference
System Connections in Rapid Toolkit for Sparkplug
Rapid Toolkit for Sparkplug > Fundamentals > System Connections in Rapid Toolkit for Sparkplug
In This Topic

Introduction

The system connection here means a connection to the Sparkplug system, facilitated by an MQTT broker. The principles of how the system connection works and how it is configured are the same, regardless of whether you are developing a Sparkplug edge node (a producer), or a Sparkplug host application (a consumer).

This article explains various forms of the Sparkplug system connection, using different protocols, and how to achieve it from the code.

Authentication with User Name and Password

The MQTT protocol allows the clients (in Sparkplug, host applications or edge nodes) to authenticate themselves to the server (MQTT broker) using a user name and an optional password.

The username and password can be specified in the broker descriptor, using the UserName Property and Password Property. Note that regardless of how the broker descriptor is constructed, the user name and password are kept in the memory in plain text, and are transferred in plain text on the wire, unless encryption is used (e.g., using TLS or WSS - see other examples). The user name and password can also be specified directly in the MQTT broker URL, using the "userinfo" subcomponent of the URL, e.g. "mqtt://admin:password@localhost".

The following examples illustrate how the Sparkplug host application and edge node can specify user name and password for their authentication to the MQTT broker.

Example (Host Application)

.NET

// This example shows how to subscribe to all metrics of a given edge node, with authentication.
//
// In order to publish or observe messages for this example, start the SparkplugEdgeNodeConsoleDemo program first.
// The username and password must match the ones used by the MQTT broker.
//
// Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-ConnectivityStudio/Latest/examples.html .
// Sparkplug examples in C# on GitHub: https://github.com/OPCLabs/Examples-ConnectivityStudio-CSharp .
// Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
// a commercial license in order to use Online Forums, and we reply to every post.

using System;
using OpcLabs.EasySparkplug;
using OpcLabs.EasySparkplug.OperationModel;

namespace SparkplugDocExamples.Consumer._EasySparkplugConsumer
{
    partial class SubscribeEdgeNodeMetric
    {
        public static void Authentication()
        {
            // The username and password can be specified in the broker descriptor, as below.
            // Note that the default port for the "mqtt" scheme is 1883.
            var brokerDescriptor = new SparkplugBrokerDescriptor("mqtt://localhost")
            {
                UserName = "admin",
                Password = "password"
            };
            var hostDescriptor = new SparkplugHostDescriptor(brokerDescriptor);

            // Alternatively, if you do not mind, the MQTT broker URL can directly include the username and password,
            // as below.
            // Note that regardless of how the broker descriptor is constructed, the username and password are transferred
            // in plain text on the wire, unless encryption is used (e.g., using TLS or WSS - see other examples).
            var hostDescriptor2 = new SparkplugHostDescriptor("mqtt://admin:password@localhost");

            // Instantiate the consumer object and hook events.
            var consumer = new EasySparkplugConsumer();
            consumer.MetricNotification += consumer_Authentication_MetricNotification;

            Console.WriteLine("Subscribing...");
            // In this example, we specify the precise Sparkplug group ID and edge node ID, but allow any metric name.
            consumer.SubscribeEdgeNodeMetric(hostDescriptor,    // or hostDescriptor2, if you prefer the alternative method
                "easyGroup", "easySparkplugDemo", "#");

            Console.WriteLine("Processing notifications for 20 seconds...");
            System.Threading.Thread.Sleep(20 * 1000);

            Console.WriteLine("Unsubscribing...");
            consumer.UnsubscribeAllMetrics();

            Console.WriteLine("Waiting for 5 seconds...");
            System.Threading.Thread.Sleep(5 * 1000);

            Console.WriteLine("Finished.");
        }


        static void consumer_Authentication_MetricNotification(object sender, EasySparkplugMetricNotificationEventArgs eventArgs)
        {
            // Handle different types of notifications.
            Console.WriteLine();
            switch (eventArgs.NotificationType)
            {
                case SparkplugNotificationType.Connect:
                    Console.WriteLine($"Connected to Sparkplug host, client ID: {eventArgs.ClientId}.");
                    break;
                case SparkplugNotificationType.Disconnect:
                    Console.WriteLine("Disconnected from Sparkplug host.");
                    break;
                case SparkplugNotificationType.Data:
                    Console.WriteLine("Received data from Sparkplug host.");
                    Console.WriteLine($"Metric name: {eventArgs.MetricName}");
                    Console.WriteLine($"Value: {eventArgs.MetricData?.Value}");
                    break;
                case SparkplugNotificationType.Birth:
                    Console.WriteLine("Received birth message from Sparkplug host.");
                    Console.WriteLine($"Metric name: {eventArgs.MetricName}");
                    Console.WriteLine($"Value: {eventArgs.MetricData?.Value}");
                    break;
                case SparkplugNotificationType.Death:
                    Console.WriteLine("Received death message from Sparkplug host.");
                    Console.WriteLine($"Metric name: {eventArgs.MetricName}");
                    break;
            }
            if (!eventArgs.Succeeded)
                Console.WriteLine($"*** Failure: {eventArgs.ErrorMessageBrief}");
        }
    }
}
' This example shows how to subscribe to all metrics of a given edge node, with authentication.
'
' In order to publish or observe messages for this example, start the SparkplugEdgeNodeConsoleDemo program first.
'
' Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-ConnectivityStudio/Latest/examples.html .
' Sparkplug examples in C# on GitHub: https://github.com/OPCLabs/Examples-ConnectivityStudio-CSharp .
' Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
' a commercial license in order to use Online Forums, and we reply to every post.

Imports OpcLabs.EasySparkplug
Imports OpcLabs.EasySparkplug.OperationModel

Namespace Global.SparkplugDocExamples.Consumer._EasySparkplugConsumer
    Partial Class SubscribeEdgeNodeMetric
        Public Shared Sub Authentication()
            ' The username and password can be specified in the broker descriptor, as below.
            ' Note that the default port for the "mqtt" scheme is 1883.
            Dim brokerDescriptor = New SparkplugBrokerDescriptor("mqtt://localhost") With {
                .UserName = "admin",
                .Password = "password"
                }
            Dim hostDescriptor = New SparkplugHostDescriptor(brokerDescriptor)

            ' Alternatively, if you do not mind, the MQTT broker URL can directly include the username and password,
            ' as below.
            ' Note that regardless of how the broker descriptor is constructed, the username and password are transferred
            ' in plain text on the wire, unless encryption is used (e.g., using TLS or WSS - see other examples).
            Dim hostDescriptor2 = New SparkplugHostDescriptor("mqtt://admin:password@localhost")

            ' Instantiate the consumer object and hook events.
            Dim consumer = New EasySparkplugConsumer()
            AddHandler consumer.MetricNotification, AddressOf consumer_Authentication_MetricNotification

            Console.WriteLine("Subscribing...")
            ' In this example, we specify the precise Sparkplug group ID and edge node ID, but allow any metric name.
            consumer.SubscribeEdgeNodeMetric(hostDescriptor, ' or hostDescriptor2, if you prefer the alternative method
                "easyGroup", "easySparkplugDemo", "#")

            Console.WriteLine("Processing notifications for 20 seconds...")
            Threading.Thread.Sleep(20 * 1000)

            Console.WriteLine("Unsubscribing...")
            consumer.UnsubscribeAllMetrics()

            Console.WriteLine("Waiting for 5 seconds...")
            Threading.Thread.Sleep(5 * 1000)

            Console.WriteLine("Finished.")
        End Sub

        Private Shared Sub consumer_Authentication_MetricNotification(ByVal sender As Object, ByVal eventArgs As EasySparkplugMetricNotificationEventArgs)
            ' Handle different types of notifications.
            Console.WriteLine()
            Select Case eventArgs.NotificationType
                Case SparkplugNotificationType.Connect
                    Console.WriteLine($"Connected to Sparkplug host, client ID: {eventArgs.ClientId}.")
                Case SparkplugNotificationType.Disconnect
                    Console.WriteLine("Disconnected from Sparkplug host.")
                Case SparkplugNotificationType.Data
                    Console.WriteLine("Received data from Sparkplug host.")
                    Console.WriteLine($"Metric name: {eventArgs.MetricName}")
                    Console.WriteLine($"Value: {eventArgs.MetricData?.Value}")
                Case SparkplugNotificationType.Birth
                    Console.WriteLine("Received birth message from Sparkplug host.")
                    Console.WriteLine($"Metric name: {eventArgs.MetricName}")
                    Console.WriteLine($"Value: {eventArgs.MetricData?.Value}")
                Case SparkplugNotificationType.Death
                    Console.WriteLine("Received death message from Sparkplug host.")
                    Console.WriteLine($"Metric name: {eventArgs.MetricName}")
            End Select
            If Not eventArgs.Succeeded Then
                Console.WriteLine($"*** Failure: {eventArgs.ErrorMessageBrief}")
            End If
        End Sub
    End Class
End Namespace

 

Example (Edge Node)

.NET

// This example shows how to create a Sparkplug edge node with a single metric, start and stop it, with authentication.
// to the broker. The username and password must match the ones used by the MQTT broker.
//
// You can use any Sparkplug application, including our SparkplugCmd utility and the SparkplugApplicationConsoleDemo
// program, to subscribe to the edge node data. 
//
// Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-ConnectivityStudio/Latest/examples.html .
// Sparkplug examples in C# on GitHub: https://github.com/OPCLabs/Examples-ConnectivityStudio-CSharp .
// Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
// a commercial license in order to use Online Forums, and we reply to every post.

using System;
using OpcLabs.EasySparkplug;
using OpcLabs.EasySparkplug.OperationModel;

namespace SparkplugDocExamples.EdgeNode._EasySparkplugEdgeNode
{
    partial class Start_Stop
    {
        static public void Authentication()
        {
            // The username and password can be specified in the broker descriptor, as below.
            // Note that the default port for the "mqtt" scheme is 1883.
            var brokerDescriptor = new SparkplugBrokerDescriptor("mqtt://localhost")
            {
                UserName = "admin",
                Password = "password"
            };
            var hostDescriptor = new SparkplugHostDescriptor(brokerDescriptor);

            // Alternatively, if you do not mind, the MQTT broker URL can directly include the username and password,
            // as below.
            // Note that regardless of how the broker descriptor is constructed, the username and password are transferred
            // in plain text on the wire, unless encryption is used (e.g., using TLS or WSS - see other examples).
            var hostDescriptor2 = new SparkplugHostDescriptor("mqtt://admin:password@localhost");

            // Instantiate the edge node object and hook events.
            var edgeNode = new EasySparkplugEdgeNode(hostDescriptor,    // or hostDescriptor2, if you prefer the alternative method
                "easyGroup", "easySparkplugDemo");
            edgeNode.SystemConnectionStateChanged += edgeNode_Authentication_SystemConnectionStateChanged;

            // Define a metric providing random integers.
            var random = new Random();
            edgeNode.Metrics.Add(new SparkplugMetric("MyMetric").ReadValueFunction(() => random.Next()));

            // Start the edge node.
            Console.WriteLine("The edge node is starting...");
            edgeNode.Start();

            Console.WriteLine("The edge node is started.");
            Console.WriteLine();

            // Let the user decide when to stop.
            Console.WriteLine("Press Enter to stop the edge node...");
            Console.ReadLine();

            // Stop the edge node.
            Console.WriteLine("The edge node is stopping...");
            edgeNode.Stop();

            Console.WriteLine("The edge node is stopped.");
        }


        static void edgeNode_Authentication_SystemConnectionStateChanged(
            object sender, 
            SparkplugConnectionStateChangedEventArgs eventArgs)
        {
            // Display the new connection state (such as when the connection to the broker succeeds or fails).
            Console.WriteLine($"{nameof(EasySparkplugEdgeNode.SystemConnectionStateChanged)}: {eventArgs}");
        }
    }
}
' This example shows how to create a Sparkplug edge node with a single metric, start and stop it, with authentication.
' to the broker. The username and password must match the ones used by the MQTT broker.
'
' You can use any Sparkplug application, including our SparkplugCmd utility and the SparkplugApplicationConsoleDemo
' program, to subscribe to the edge node data.
'
' Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-ConnectivityStudio/Latest/examples.html .
' Sparkplug examples in C# on GitHub: https://github.com/OPCLabs/Examples-ConnectivityStudio-CSharp .
' Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
' a commercial license in order to use Online Forums, and we reply to every post.

Imports OpcLabs.EasySparkplug
Imports OpcLabs.EasySparkplug.OperationModel

Namespace Global.SparkplugDocExamples.EdgeNode._EasySparkplugEdgeNode
    Partial Class Start_Stop
        Public Shared Sub Authentication()
            ' The username and password can be specified in the broker descriptor, as below.
            ' Note that the default port for the "mqtt" scheme is 1883.
            Dim brokerDescriptor = New SparkplugBrokerDescriptor("mqtt://localhost") With
            {
                .UserName = "admin",
                .Password = "password"
            }
            Dim hostDescriptor = New SparkplugHostDescriptor(brokerDescriptor)

            ' Alternatively, if you do not mind, the MQTT broker URL can directly include the username and password,
            ' as below.
            ' Note that regardless of how the broker descriptor is constructed, the username and password are transferred
            ' in plain text on the wire, unless encryption is used (e.g., using TLS or WSS - see other examples).
            Dim hostDescriptor2 = New SparkplugHostDescriptor("mqtt://admin:password@localhost")

            ' Instantiate the edge node object and hook events.
            Dim edgeNode = New EasySparkplugEdgeNode(hostDescriptor, ' or hostDescriptor2, if you prefer the alternative method
                                                     "easyGroup", "easySparkplugDemo")
            AddHandler edgeNode.SystemConnectionStateChanged, AddressOf edgeNode_Authentication_SystemConnectionStateChanged

            ' Define a metric providing random integers.
            Dim random = New Random()
            edgeNode.Metrics.Add(New SparkplugMetric("MyMetric").ReadValueFunction(Function() random.Next()))

            ' Start the edge node.
            Console.WriteLine("The edge node is starting...")
            edgeNode.Start()

            Console.WriteLine("The edge node is started.")
            Console.WriteLine()

            ' Let the user decide when to stop.
            Console.WriteLine("Press Enter to stop the edge node...")
            Console.ReadLine()

            ' Stop the edge node.
            Console.WriteLine("The edge node is stopping...")
            edgeNode.Stop()

            Console.WriteLine("The edge node is stopped.")
        End Sub

        Private Shared Sub edgeNode_Authentication_SystemConnectionStateChanged _
            (ByVal sender As Object, ByVal eventArgs As SparkplugConnectionStateChangedEventArgs)
            ' Display the new connection state (such as when the connection to the broker succeeds or fails).
            Console.WriteLine($"{NameOf(EasySparkplugEdgeNode.SystemConnectionStateChanged)}: {eventArgs}")
        End Sub
    End Class
End Namespace

 

Obviously, such authentication can be combined with other variants of the MQTT connection (described below), such as TLS or WebSocket.

Selecting MQTT 5 or Other Version

Rapid Toolkit for Sparkplug supports multiple MQTT versions (see Rapid Toolkit for Sparkplug Specifications). By default, Rapid Toolkit for Sparkplug connects to the broker using MQTT version 3.1.1. You can choose a different versions, e.g. because your MQTT broker does not support the default MQTT version, or because you have an MQTT broker that supports a higher version of MQTT, and you want to benefit from the features of the newer MQTT protocol version.

You can choose a specific MQTT protocol version in two ways:

The code illustrating the use of both these methods can be seen in the examples below.

Example (Host Application)

.NET

// This example shows how to subscribe to all metrics of a given edge node using MQTT version 5.0.
//
// In order to publish or observe messages for this example, start the SparkplugEdgeNodeConsoleDemo program first.
//
// Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-ConnectivityStudio/Latest/examples.html .
// Sparkplug examples in C# on GitHub: https://github.com/OPCLabs/Examples-ConnectivityStudio-CSharp .
// Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
// a commercial license in order to use Online Forums, and we reply to every post.

using System;
using OpcLabs.EasySparkplug;
using OpcLabs.EasySparkplug.OperationModel;

namespace SparkplugDocExamples.Consumer._EasySparkplugConsumer
{
    partial class SubscribeEdgeNodeMetric
    {
        public static void Mqtt5()
        {
            // The MQTT protocol version can be specified in the broker URL using the "version" query parameter, as below.
            // Possible values are 310, 311, and 500, which correspond to MQTT 3.1, MQTT 3.1.1, and MQTT 5.0, respectively.
            // The default is MQTT 3.1.1.
            // Note that the default port for the "mqtt" scheme is 1883.
            var hostDescriptor = new SparkplugHostDescriptor("mqtt://localhost?version=500");

            // Alternatively, if you cannot or do not want to manipulate the broker URL, set a custom property in the
            // broker descriptor, as below. This method is subject to change with the implementation of the Sparkplug
            // component provider. Use value 3 for MQTT 3.1, 4 for MQTT 3.1.1, and 5 for MQTT 5.0.
            var brokerDescriptor = new SparkplugBrokerDescriptor("mqtt://localhost")
                {
                    CustomPropertyValueDictionary =
                    {
                        ["NetSparkplugComponentProvider.MqttClientOptions.ProtocolVersion"] = 5
                    }
                };
            // Create the host descriptor for the alternative method.
            var hostDescriptor2 = new SparkplugHostDescriptor(brokerDescriptor);
            
            // Instantiate the consumer object and hook events.
            var consumer = new EasySparkplugConsumer();
            consumer.MetricNotification += consumer_Mqtt5_MetricNotification;

            Console.WriteLine("Subscribing...");
            // In this example, we specify the precise Sparkplug group ID and edge node ID, but allow any metric name.
            consumer.SubscribeEdgeNodeMetric(hostDescriptor,    // or hostDescriptor2, if you prefer the alternative method
                "easyGroup", "easySparkplugDemo", "#");

            Console.WriteLine("Processing notifications for 20 seconds...");
            System.Threading.Thread.Sleep(20 * 1000);

            Console.WriteLine("Unsubscribing...");
            consumer.UnsubscribeAllMetrics();

            Console.WriteLine("Waiting for 5 seconds...");
            System.Threading.Thread.Sleep(5 * 1000);

            Console.WriteLine("Finished.");
        }


        static void consumer_Mqtt5_MetricNotification(object sender, EasySparkplugMetricNotificationEventArgs eventArgs)
        {
            // Handle different types of notifications.
            Console.WriteLine();
            switch (eventArgs.NotificationType)
            {
                case SparkplugNotificationType.Connect:
                    Console.WriteLine($"Connected to Sparkplug host, client ID: {eventArgs.ClientId}.");
                    break;
                case SparkplugNotificationType.Disconnect:
                    Console.WriteLine("Disconnected from Sparkplug host.");
                    break;
                case SparkplugNotificationType.Data:
                    Console.WriteLine("Received data from Sparkplug host.");
                    Console.WriteLine($"Metric name: {eventArgs.MetricName}");
                    Console.WriteLine($"Value: {eventArgs.MetricData?.Value}");
                    break;
                case SparkplugNotificationType.Birth:
                    Console.WriteLine("Received birth message from Sparkplug host.");
                    Console.WriteLine($"Metric name: {eventArgs.MetricName}");
                    Console.WriteLine($"Value: {eventArgs.MetricData?.Value}");
                    break;
                case SparkplugNotificationType.Death:
                    Console.WriteLine("Received death message from Sparkplug host.");
                    Console.WriteLine($"Metric name: {eventArgs.MetricName}");
                    break;
            }
            if (!eventArgs.Succeeded)
                Console.WriteLine($"*** Failure: {eventArgs.ErrorMessageBrief}");
        }
    }
}
' This example shows how to subscribe to all metrics of a given edge node using MQTT version 5.0.
'
' In order to publish or observe messages for this example, start the SparkplugEdgeNodeConsoleDemo program first.
'
' Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-ConnectivityStudio/Latest/examples.html .
' Sparkplug examples in C# on GitHub: https://github.com/OPCLabs/Examples-ConnectivityStudio-CSharp .
' Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
' a commercial license in order to use Online Forums, and we reply to every post.

Imports OpcLabs.EasySparkplug
Imports OpcLabs.EasySparkplug.OperationModel

Namespace Global.SparkplugDocExamples.Consumer._EasySparkplugConsumer
    Partial Class SubscribeEdgeNodeMetric
        Public Shared Sub Mqtt5()
            ' The MQTT protocol version can be specified in the broker URL using the "version" query parameter, as below.
            ' Possible values are 310, 311, and 500, which correspond to MQTT 3.1, MQTT 3.1.1, and MQTT 5.0, respectively.
            ' The default is MQTT 3.1.1.
            ' Note that the default port for the "mqtt" scheme is 1883.
            Dim hostDescriptor = New SparkplugHostDescriptor("mqtt://localhost?version=500")

            ' Alternatively, if you cannot or do not want to manipulate the broker URL, set a custom property in the
            ' broker descriptor, as below. This method is subject to change with the implementation of the Sparkplug
            ' component provider. Use value 3 for MQTT 3.1, 4 for MQTT 3.1.1, and 5 for MQTT 5.0.
            Dim brokerDescriptor = New SparkplugBrokerDescriptor("mqtt://localhost")
            brokerDescriptor.CustomPropertyValueDictionary.Add("NetSparkplugComponentProvider.MqttClientOptions.ProtocolVersion", 5)

            ' Create the host descriptor for the alternative method.
            Dim hostDescriptor2 = New SparkplugHostDescriptor(brokerDescriptor)

            ' Instantiate the consumer object and hook events.
            Dim consumer = New EasySparkplugConsumer()
            AddHandler consumer.MetricNotification, AddressOf consumer_Mqtt5_MetricNotification

            Console.WriteLine("Subscribing...")
            ' In this example, we specify the precise Sparkplug group ID and edge node ID, but allow any metric name.
            consumer.SubscribeEdgeNodeMetric(hostDescriptor, ' or hostDescriptor2, if you prefer the alternative method
                "easyGroup", "easySparkplugDemo", "#")

            Console.WriteLine("Processing notifications for 20 seconds...")
            Threading.Thread.Sleep(20 * 1000)

            Console.WriteLine("Unsubscribing...")
            consumer.UnsubscribeAllMetrics()

            Console.WriteLine("Waiting for 5 seconds...")
            Threading.Thread.Sleep(5 * 1000)

            Console.WriteLine("Finished.")
        End Sub

        Private Shared Sub consumer_Mqtt5_MetricNotification(ByVal sender As Object, ByVal eventArgs As EasySparkplugMetricNotificationEventArgs)
            ' Handle different types of notifications.
            Console.WriteLine()
            Select Case eventArgs.NotificationType
                Case SparkplugNotificationType.Connect
                    Console.WriteLine($"Connected to Sparkplug host, client ID: {eventArgs.ClientId}.")
                Case SparkplugNotificationType.Disconnect
                    Console.WriteLine("Disconnected from Sparkplug host.")
                Case SparkplugNotificationType.Data
                    Console.WriteLine("Received data from Sparkplug host.")
                    Console.WriteLine($"Metric name: {eventArgs.MetricName}")
                    Console.WriteLine($"Value: {eventArgs.MetricData?.Value}")
                Case SparkplugNotificationType.Birth
                    Console.WriteLine("Received birth message from Sparkplug host.")
                    Console.WriteLine($"Metric name: {eventArgs.MetricName}")
                    Console.WriteLine($"Value: {eventArgs.MetricData?.Value}")
                Case SparkplugNotificationType.Death
                    Console.WriteLine("Received death message from Sparkplug host.")
                    Console.WriteLine($"Metric name: {eventArgs.MetricName}")
            End Select
            If Not eventArgs.Succeeded Then
                Console.WriteLine($"*** Failure: {eventArgs.ErrorMessageBrief}")
            End If
        End Sub
    End Class
End Namespace

 

Example (Edge Node)

.NET

// This example shows how to create a Sparkplug edge node with a single metric, start and stop it, using MQTT version 5.0.
//
// You can use any Sparkplug application, including our SparkplugCmd utility and the SparkplugApplicationConsoleDemo
// program, to subscribe to the edge node data. 
//
// Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-ConnectivityStudio/Latest/examples.html .
// Sparkplug examples in C# on GitHub: https://github.com/OPCLabs/Examples-ConnectivityStudio-CSharp .
// Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
// a commercial license in order to use Online Forums, and we reply to every post.

using System;
using OpcLabs.EasySparkplug;
using OpcLabs.EasySparkplug.OperationModel;

namespace SparkplugDocExamples.EdgeNode._EasySparkplugEdgeNode
{
    partial class Start_Stop
    {
        static public void Mqtt5()
        {
            // The MQTT protocol version can be specified in the broker URL using the "version" query parameter, as below.
            // Possible values are 310, 311, and 500, which correspond to MQTT 3.1, MQTT 3.1.1, and MQTT 5.0, respectively.
            // The default is MQTT 3.1.1.
            // Note that the default port for the "mqtt" scheme is 1883.
            var hostDescriptor = new SparkplugHostDescriptor("mqtt://localhost?version=500");

            // Alternatively, if you cannot or do not want to manipulate the broker URL, set a custom property in the
            // broker descriptor, as below. This method is subject to change with the implementation of the Sparkplug
            // component provider. Use value 3 for MQTT 3.1, 4 for MQTT 3.1.1, and 5 for MQTT 5.0.
            var brokerDescriptor = new SparkplugBrokerDescriptor("mqtt://localhost")
            {
                CustomPropertyValueDictionary =
                {
                    ["NetSparkplugComponentProvider.MqttClientOptions.ProtocolVersion"] = 5
                }
            };
            // Create the host descriptor for the alternative method.
            var hostDescriptor2 = new SparkplugHostDescriptor(brokerDescriptor);

            // Instantiate the edge node object and hook events.
            var edgeNode = new EasySparkplugEdgeNode(hostDescriptor,    // or hostDescriptor2, if you prefer the alternative method
                "easyGroup", "easySparkplugDemo");
            edgeNode.SystemConnectionStateChanged += edgeNode_Mqtt5_SystemConnectionStateChanged;

            // Define a metric providing random integers.
            var random = new Random();
            edgeNode.Metrics.Add(new SparkplugMetric("MyMetric").ReadValueFunction(() => random.Next()));

            // Start the edge node.
            Console.WriteLine("The edge node is starting...");
            edgeNode.Start();

            Console.WriteLine("The edge node is started.");
            Console.WriteLine();

            // Let the user decide when to stop.
            Console.WriteLine("Press Enter to stop the edge node...");
            Console.ReadLine();

            // Stop the edge node.
            Console.WriteLine("The edge node is stopping...");
            edgeNode.Stop();

            Console.WriteLine("The edge node is stopped.");
        }


        static void edgeNode_Mqtt5_SystemConnectionStateChanged(
            object sender, 
            SparkplugConnectionStateChangedEventArgs eventArgs)
        {
            // Display the new connection state (such as when the connection to the broker succeeds or fails).
            Console.WriteLine($"{nameof(EasySparkplugEdgeNode.SystemConnectionStateChanged)}: {eventArgs}");
        }
    }
}
' This example shows how to create a Sparkplug edge node with a single metric, start and stop it, using MQTT version 5.0.
'
' You can use any Sparkplug application, including our SparkplugCmd utility and the SparkplugApplicationConsoleDemo
' program, to subscribe to the edge node data.
'
' Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-ConnectivityStudio/Latest/examples.html .
' Sparkplug examples in C# on GitHub: https://github.com/OPCLabs/Examples-ConnectivityStudio-CSharp .
' Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
' a commercial license in order to use Online Forums, and we reply to every post.

Imports OpcLabs.EasySparkplug
Imports OpcLabs.EasySparkplug.OperationModel

Namespace Global.SparkplugDocExamples.EdgeNode._EasySparkplugEdgeNode
    Partial Class Start_Stop
        Public Shared Sub Mqtt5()
            ' The MQTT protocol version can be specified in the broker URL using the "version" query parameter, as below.
            ' Possible values are 310, 311, and 500, which correspond to MQTT 3.1, MQTT 3.1.1, and MQTT 5.0, respectively.
            ' The default is MQTT 3.1.1.
            ' Note that the default port for the "mqtt" scheme is 1883.
            Dim hostDescriptor = New SparkplugHostDescriptor("mqtt://localhost?version=500")

            ' Alternatively, if you cannot or do not want to manipulate the broker URL, set a custom property in the
            ' broker descriptor, as below. This method is subject to change with the implementation of the Sparkplug
            ' component provider. Use value 3 for MQTT 3.1, 4 for MQTT 3.1.1, and 5 for MQTT 5.0.
            Dim brokerDescriptor = New SparkplugBrokerDescriptor("mqtt://localhost")
            brokerDescriptor.CustomPropertyValueDictionary.Add("NetSparkplugComponentProvider.MqttClientOptions.ProtocolVersion", 5)

            ' Create the host descriptor for the alternative method.
            Dim hostDescriptor2 = New SparkplugHostDescriptor(brokerDescriptor)

            ' Instantiate the edge node object and hook events.
            Dim edgeNode = New EasySparkplugEdgeNode(hostDescriptor, ' or hostDescriptor2, if you prefer the alternative method
                                                     "easyGroup", "easySparkplugDemo")
            AddHandler edgeNode.SystemConnectionStateChanged, AddressOf edgeNode_Mqtt5_SystemConnectionStateChanged

            ' Define a metric providing random integers.
            Dim random = New Random()
            edgeNode.Metrics.Add(New SparkplugMetric("MyMetric").ReadValueFunction(Function() random.Next()))

            ' Start the edge node.
            Console.WriteLine("The edge node is starting...")
            edgeNode.Start()

            Console.WriteLine("The edge node is started.")
            Console.WriteLine()

            ' Let the user decide when to stop.
            Console.WriteLine("Press Enter to stop the edge node...")
            Console.ReadLine()

            ' Stop the edge node.
            Console.WriteLine("The edge node is stopping...")
            edgeNode.Stop()

            Console.WriteLine("The edge node is stopped.")
        End Sub

        Private Shared Sub edgeNode_Mqtt5_SystemConnectionStateChanged _
            (ByVal sender As Object, ByVal eventArgs As SparkplugConnectionStateChangedEventArgs)
            ' Display the new connection state (such as when the connection to the broker succeeds or fails).
            Console.WriteLine($"{NameOf(EasySparkplugEdgeNode.SystemConnectionStateChanged)}: {eventArgs}")
        End Sub
    End Class
End Namespace

 

Connecting to MQTT Broker with TLS

The TLS protocol can be specified in the broker URL using the "mqtts", "ssl" or "tls" scheme (the schemes are equivalent). With these schemes, the default port is 8883.

TLS makes use of cryptographic certificates, and requires certificate validation. In Rapid Toolkit for Sparkplug, this is done using the Certificate security plugin. Under certain conditions, and when enabled, an Unsolicited User Interaction for MQTT can be injected into your application - typically, so that the interactive user can validate a remote broker certificate, or provide a local (own) certificate.

The examples below show a Sparkplug host application and a Sprakplug edge connecting to the MQTT broker with TLS. A console interaction is enabled so that the user can validate the broker certificate if needed.

Example (Host Application)

.NET

// This example shows how to subscribe to all metrics of a given edge node using TLS.
//
// In order to publish or observe messages for this example, start the SparkplugEdgeNodeConsoleDemo program first.
// The MQTT broker may need additional configuration to support TLS connections, such as enabling the TLS listener.
//
// Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-ConnectivityStudio/Latest/examples.html .
// Sparkplug examples in C# on GitHub: https://github.com/OPCLabs/Examples-ConnectivityStudio-CSharp .
// Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
// a commercial license in order to use Online Forums, and we reply to every post.

using System;
using OpcLabs.BaseLib;
using OpcLabs.EasySparkplug;
using OpcLabs.EasySparkplug.OperationModel;
using OpcLabs.EasySparkplug.System;

namespace SparkplugDocExamples.Consumer._EasySparkplugConsumer
{
    partial class SubscribeEdgeNodeMetric
    {
        public static void Tls()
        {
            // The TLS protocol can be specified in the broker URL using the "mqtts", "ssl" or "tls" scheme, as below.
            // (the schemes are equivalent). Default port is 8883.
            var hostDescriptor = new SparkplugHostDescriptor("mqtts://localhost");

            // Enable the console interaction. The interactive user will then be able to validate remote certificates and/or
            // specify local certificate(s) to use.
            ComponentParameters componentParameters = EasySparkplugInfrastructure.Instance.Parameters;
            componentParameters.PluginSetups.FindName("ConsoleInteraction").Enabled = true;

            // By default, the local certificates, if needed, are provided by parameterized querying of certificate stores.
            // The statement below disables this, and the local certificate(s) will be specified interactively by the user.
            // For more information, see https://kb.opclabs.com/Certificate_security_plugin .
            //componentParameters.PluginConfigurations.Find<CertificateSecurityParameters>().AllowStatic = false;

            // Instantiate the consumer object and hook events.
            var consumer = new EasySparkplugConsumer();
            consumer.MetricNotification += consumer_Tls_MetricNotification;

            Console.WriteLine("Subscribing...");
            // In this example, we specify the precise Sparkplug group ID and edge node ID, but allow any metric name.
            consumer.SubscribeEdgeNodeMetric(hostDescriptor,
                "easyGroup", "easySparkplugDemo", "#");

            Console.WriteLine("Processing notifications for 20 seconds...");
            System.Threading.Thread.Sleep(20 * 1000);

            Console.WriteLine("Unsubscribing...");
            consumer.UnsubscribeAllMetrics();

            Console.WriteLine("Waiting for 5 seconds...");
            System.Threading.Thread.Sleep(5 * 1000);

            Console.WriteLine("Finished.");
        }


        static void consumer_Tls_MetricNotification(object sender, EasySparkplugMetricNotificationEventArgs eventArgs)
        {
            // Handle different types of notifications.
            Console.WriteLine();
            switch (eventArgs.NotificationType)
            {
                case SparkplugNotificationType.Connect:
                    Console.WriteLine($"Connected to Sparkplug host, client ID: {eventArgs.ClientId}.");
                    break;
                case SparkplugNotificationType.Disconnect:
                    Console.WriteLine("Disconnected from Sparkplug host.");
                    break;
                case SparkplugNotificationType.Data:
                    Console.WriteLine("Received data from Sparkplug host.");
                    Console.WriteLine($"Metric name: {eventArgs.MetricName}");
                    Console.WriteLine($"Value: {eventArgs.MetricData?.Value}");
                    break;
                case SparkplugNotificationType.Birth:
                    Console.WriteLine("Received birth message from Sparkplug host.");
                    Console.WriteLine($"Metric name: {eventArgs.MetricName}");
                    Console.WriteLine($"Value: {eventArgs.MetricData?.Value}");
                    break;
                case SparkplugNotificationType.Death:
                    Console.WriteLine("Received death message from Sparkplug host.");
                    Console.WriteLine($"Metric name: {eventArgs.MetricName}");
                    break;
            }
            if (!eventArgs.Succeeded)
                Console.WriteLine($"*** Failure: {eventArgs.ErrorMessageBrief}");
        }
    }
}
' This example shows how to subscribe to all metrics of a given edge node using TLS.
'
' In order to publish or observe messages for this example, start the SparkplugEdgeNodeConsoleDemo program first.
'
' Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-ConnectivityStudio/Latest/examples.html .
' Sparkplug examples in C# on GitHub: https://github.com/OPCLabs/Examples-ConnectivityStudio-CSharp .
' Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
' a commercial license in order to use Online Forums, and we reply to every post.

Imports System
Imports OpcLabs.BaseLib
Imports OpcLabs.BaseLib.Security
Imports OpcLabs.EasySparkplug
Imports OpcLabs.EasySparkplug.OperationModel
Imports OpcLabs.EasySparkplug.System

Namespace Global.SparkplugDocExamples.Consumer._EasySparkplugConsumer
    Partial Class SubscribeEdgeNodeMetric
        Public Shared Sub Tls()
            ' The TLS protocol can be specified in the broker URL using the "mqtts", "ssl" or "tls" scheme, as below.
            ' (the schemes are equivalent). Default port is 8883.
            Dim hostDescriptor = New SparkplugHostDescriptor("mqtts://localhost")

            ' Enable the console interaction. The interactive user will then be able to validate remote certificates and/or
            ' specify local certificate(s) to use.
            Dim componentParameters As ComponentParameters = EasySparkplugInfrastructure.Instance.Parameters
            componentParameters.PluginSetups.FindName("ConsoleInteraction").Enabled = True

            ' By default, the local certificates, if needed, are provided by parameterized querying of certificate stores.
            ' The statement below disables this, and the local certificate(s) will be specified interactively by the user.
            ' For more information, see https://kb.opclabs.com/Certificate_security_plugin .
            'componentParameters.PluginConfigurations.Find(Of CertificateSecurityParameters)().AllowStatic = False

            ' Instantiate the consumer object and hook events.
            Dim consumer = New EasySparkplugConsumer()
            AddHandler consumer.MetricNotification, AddressOf consumer_Tls_MetricNotification

            Console.WriteLine("Subscribing...")
            ' In this example, we specify the precise Sparkplug group ID and edge node ID, but allow any metric name.
            consumer.SubscribeEdgeNodeMetric(hostDescriptor,
                "easyGroup", "easySparkplugDemo", "#")

            Console.WriteLine("Processing notifications for 20 seconds...")
            Threading.Thread.Sleep(20 * 1000)

            Console.WriteLine("Unsubscribing...")
            consumer.UnsubscribeAllMetrics()

            Console.WriteLine("Waiting for 5 seconds...")
            Threading.Thread.Sleep(5 * 1000)

            Console.WriteLine("Finished.")
        End Sub

        Private Shared Sub consumer_Tls_MetricNotification(ByVal sender As Object, ByVal eventArgs As EasySparkplugMetricNotificationEventArgs)
            ' Handle different types of notifications.
            Console.WriteLine()
            Select Case eventArgs.NotificationType
                Case SparkplugNotificationType.Connect
                    Console.WriteLine($"Connected to Sparkplug host, client ID: {eventArgs.ClientId}.")
                Case SparkplugNotificationType.Disconnect
                    Console.WriteLine("Disconnected from Sparkplug host.")
                Case SparkplugNotificationType.Data
                    Console.WriteLine("Received data from Sparkplug host.")
                    Console.WriteLine($"Metric name: {eventArgs.MetricName}")
                    Console.WriteLine($"Value: {eventArgs.MetricData?.Value}")
                Case SparkplugNotificationType.Birth
                    Console.WriteLine("Received birth message from Sparkplug host.")
                    Console.WriteLine($"Metric name: {eventArgs.MetricName}")
                    Console.WriteLine($"Value: {eventArgs.MetricData?.Value}")
                Case SparkplugNotificationType.Death
                    Console.WriteLine("Received death message from Sparkplug host.")
                    Console.WriteLine($"Metric name: {eventArgs.MetricName}")
            End Select
            If Not eventArgs.Succeeded Then
                Console.WriteLine($"*** Failure: {eventArgs.ErrorMessageBrief}")
            End If
        End Sub
    End Class
End Namespace

 

Example (Edge Node)

.NET

// This example shows how to create a Sparkplug edge node with a single metric, start and stop it, using TLS.
//
// You can use any Sparkplug application, including our SparkplugCmd utility and the SparkplugApplicationConsoleDemo
// program, to subscribe to the edge node data. 
// The MQTT broker may need additional configuration to support TLS connections, such as enabling the TLS listener.
//
// Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-ConnectivityStudio/Latest/examples.html .
// Sparkplug examples in C# on GitHub: https://github.com/OPCLabs/Examples-ConnectivityStudio-CSharp .
// Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
// a commercial license in order to use Online Forums, and we reply to every post.

using System;
using OpcLabs.BaseLib;
using OpcLabs.EasySparkplug;
using OpcLabs.EasySparkplug.OperationModel;
using OpcLabs.EasySparkplug.System;

namespace SparkplugDocExamples.EdgeNode._EasySparkplugEdgeNode
{
    partial class Start_Stop
    {
        static public void Tls()
        {
            // The TLS protocol can be specified in the broker URL using the "mqtts", "ssl" or "tls" scheme, as below.
            // (the schemes are equivalent). Default port is 8883.
            var hostDescriptor = new SparkplugHostDescriptor("mqtts://localhost");

            // Enable the console interaction by the component. The interactive user will then be able to validate remote
            // certificates and/or specify local certificate(s) to use.
            ComponentParameters componentParameters = EasySparkplugInfrastructure.Instance.Parameters;
            componentParameters.PluginSetups.FindName("ConsoleInteraction").Enabled = true;

            // By default, the local certificates, if needed, are provided by parameterized querying of certificate stores.
            // The statement below disables this, and the local certificate(s) will be specified interactively by the user.
            // For more information, see https://kb.opclabs.com/Certificate_security_plugin .
            //componentParameters.PluginConfigurations.Find<CertificateSecurityParameters>().AllowStatic = false;

            // Instantiate the edge node object and hook events.
            var edgeNode = new EasySparkplugEdgeNode(hostDescriptor,
                "easyGroup", "easySparkplugDemo");
            edgeNode.SystemConnectionStateChanged += edgeNode_Tls_SystemConnectionStateChanged;

            // Define a metric providing random integers.
            var random = new Random();
            edgeNode.Metrics.Add(new SparkplugMetric("MyMetric").ReadValueFunction(() => random.Next()));

            // Start the edge node.
            Console.WriteLine("The edge node is starting...");
            edgeNode.Start();

            Console.WriteLine("The edge node is started.");
            Console.WriteLine();

            // We do not use Console.ReadLine() to let the user decide when to stop, because it can collide with the
            // certificate security console interaction.
            Console.WriteLine("Waiting for 30 seconds...");
            System.Threading.Thread.Sleep(30 * 1000);

            // Stop the edge node.
            Console.WriteLine("The edge node is stopping...");
            edgeNode.Stop();

            Console.WriteLine("The edge node is stopped.");
        }


        static void edgeNode_Tls_SystemConnectionStateChanged(
            object sender, 
            SparkplugConnectionStateChangedEventArgs eventArgs)
        {
            // Display the new connection state (such as when the connection to the broker succeeds or fails).
            Console.WriteLine($"{nameof(EasySparkplugEdgeNode.SystemConnectionStateChanged)}: {eventArgs}");
        }
    }
}
' This example shows how to create a Sparkplug edge node with a single metric, start and stop it, using TLS.
'
' You can use any Sparkplug application, including our SparkplugCmd utility and the SparkplugApplicationConsoleDemo
' program, to subscribe to the edge node data.
' The MQTT broker may need additional configuration to support TLS connections, such as enabling the TLS listener.
'
' Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-ConnectivityStudio/Latest/examples.html .
' Sparkplug examples in C# on GitHub: https://github.com/OPCLabs/Examples-ConnectivityStudio-CSharp .
' Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
' a commercial license in order to use Online Forums, and we reply to every post.

Imports System
Imports OpcLabs.BaseLib
Imports OpcLabs.BaseLib.Security
Imports OpcLabs.EasySparkplug
Imports OpcLabs.EasySparkplug.OperationModel
Imports OpcLabs.EasySparkplug.System

Namespace Global.SparkplugDocExamples.EdgeNode._EasySparkplugEdgeNode
    Partial Class Start_Stop
        Public Shared Sub Tls()
            ' The TLS protocol can be specified in the broker URL using the "mqtts", "ssl" or "tls" scheme, as below.
            ' (the schemes are equivalent). Default port is 8883.
            Dim hostDescriptor = New SparkplugHostDescriptor("mqtts://localhost")

            ' Enable the console interaction by the component. The interactive user will then be able to validate remote
            ' certificates and/or specify local certificate(s) to use.
            Dim componentParameters As ComponentParameters = EasySparkplugInfrastructure.Instance.Parameters
            componentParameters.PluginSetups.FindName("ConsoleInteraction").Enabled = True

            ' By default, the local certificates, if needed, are provided by parameterized querying of certificate stores.
            ' The statement below disables this, and the local certificate(s) will be specified interactively by the user.
            ' For more information, see https://kb.opclabs.com/Certificate_security_plugin .
            'componentParameters.PluginConfigurations.Find(Of CertificateSecurityParameters)().AllowStatic = False

            ' Instantiate the edge node object and hook events.
            Dim edgeNode = New EasySparkplugEdgeNode(hostDescriptor,
                                                     "easyGroup", "easySparkplugDemo")
            AddHandler edgeNode.SystemConnectionStateChanged, AddressOf edgeNode_Tls_SystemConnectionStateChanged

            ' Define a metric providing random integers.
            Dim random = New Random()
            edgeNode.Metrics.Add(New SparkplugMetric("MyMetric").ReadValueFunction(Function() random.Next()))

            ' Start the edge node.
            Console.WriteLine("The edge node is starting...")
            edgeNode.Start()

            Console.WriteLine("The edge node is started.")
            Console.WriteLine()

            ' We do not use Console.ReadLine() to let the user decide when to stop, because it can collide with the
            ' certificate security console interaction.
            Console.WriteLine("Waiting for 30 seconds...")
            System.Threading.Thread.Sleep(30 * 1000)

            ' Stop the edge node.
            Console.WriteLine("The edge node is stopping...")
            edgeNode.Stop()

            Console.WriteLine("The edge node is stopped.")
        End Sub

        Private Shared Sub edgeNode_Tls_SystemConnectionStateChanged _
            (ByVal sender As Object, ByVal eventArgs As SparkplugConnectionStateChangedEventArgs)
            ' Display the new connection state (such as when the connection to the broker succeeds or fails).
            Console.WriteLine($"{NameOf(EasySparkplugEdgeNode.SystemConnectionStateChanged)}: {eventArgs}")
        End Sub
    End Class
End Namespace

 

Connecting to MQTT Broker via WebSocket

The WebSocket protocol can be specified in the broker URL using the "ws" scheme, or "wss" for WebSocket Secure. Default port for "ws" is 80, and for "wss" it is 443. For secure WebSocket, similar considerations relating to cryptographic certificates apply as described above with TLS.

Use of the WebSocket protocol is illustrated in the following examples.

Example (Host Application)

.NET

// This example shows how to subscribe to all metrics of a given edge node using WebSocket.
//
// In order to publish or observe messages for this example, start the SparkplugEdgeNodeConsoleDemo program first.
// The MQTT broker may need additional configuration to support WebSocket connections, such as enabling the WebSocket port
// and setting up the path.
//
// Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-ConnectivityStudio/Latest/examples.html .
// Sparkplug examples in C# on GitHub: https://github.com/OPCLabs/Examples-ConnectivityStudio-CSharp .
// Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
// a commercial license in order to use Online Forums, and we reply to every post.

using System;
using OpcLabs.EasySparkplug;
using OpcLabs.EasySparkplug.OperationModel;

namespace SparkplugDocExamples.Consumer._EasySparkplugConsumer
{
    partial class SubscribeEdgeNodeMetric
    {
        public static void WebSocket()
        {
            // The WebSocket protocol can be specified in the broker URL using the "ws" scheme, as below.
            // Note: Use the "wss" scheme for WebSocket Secure. Default port for "ws" is 80, and for "wss" is 443.
            var hostDescriptor = new SparkplugHostDescriptor("ws://localhost:8080/mqtt");
            
            // Instantiate the consumer object and hook events.
            var consumer = new EasySparkplugConsumer();
            consumer.MetricNotification += consumer_WebSocket_MetricNotification;

            Console.WriteLine("Subscribing...");
            // In this example, we specify the precise Sparkplug group ID and edge node ID, but allow any metric name.
            consumer.SubscribeEdgeNodeMetric(hostDescriptor,
                "easyGroup", "easySparkplugDemo", "#");

            Console.WriteLine("Processing notifications for 20 seconds...");
            System.Threading.Thread.Sleep(20 * 1000);

            Console.WriteLine("Unsubscribing...");
            consumer.UnsubscribeAllMetrics();

            Console.WriteLine("Waiting for 5 seconds...");
            System.Threading.Thread.Sleep(5 * 1000);

            Console.WriteLine("Finished.");
        }


        static void consumer_WebSocket_MetricNotification(object sender, EasySparkplugMetricNotificationEventArgs eventArgs)
        {
            // Handle different types of notifications.
            Console.WriteLine();
            switch (eventArgs.NotificationType)
            {
                case SparkplugNotificationType.Connect:
                    Console.WriteLine($"Connected to Sparkplug host, client ID: {eventArgs.ClientId}.");
                    break;
                case SparkplugNotificationType.Disconnect:
                    Console.WriteLine("Disconnected from Sparkplug host.");
                    break;
                case SparkplugNotificationType.Data:
                    Console.WriteLine("Received data from Sparkplug host.");
                    Console.WriteLine($"Metric name: {eventArgs.MetricName}");
                    Console.WriteLine($"Value: {eventArgs.MetricData?.Value}");
                    break;
                case SparkplugNotificationType.Birth:
                    Console.WriteLine("Received birth message from Sparkplug host.");
                    Console.WriteLine($"Metric name: {eventArgs.MetricName}");
                    Console.WriteLine($"Value: {eventArgs.MetricData?.Value}");
                    break;
                case SparkplugNotificationType.Death:
                    Console.WriteLine("Received death message from Sparkplug host.");
                    Console.WriteLine($"Metric name: {eventArgs.MetricName}");
                    break;
            }
            if (!eventArgs.Succeeded)
                Console.WriteLine($"*** Failure: {eventArgs.ErrorMessageBrief}");
        }
    }
}
' This example shows how to subscribe to all metrics of a given edge node using WebSocket.
'
' In order to publish or observe messages for this example, start the SparkplugEdgeNodeConsoleDemo program first.
'
' Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-ConnectivityStudio/Latest/examples.html .
' Sparkplug examples in C# on GitHub: https://github.com/OPCLabs/Examples-ConnectivityStudio-CSharp .
' Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
' a commercial license in order to use Online Forums, and we reply to every post.

Imports OpcLabs.EasySparkplug
Imports OpcLabs.EasySparkplug.OperationModel

Namespace Global.SparkplugDocExamples.Consumer._EasySparkplugConsumer
    Partial Class SubscribeEdgeNodeMetric
        Public Shared Sub WebSocket()
            ' The WebSocket protocol can be specified in the broker URL using the "ws" scheme, as below.
            ' Note: Use the "wss" scheme for WebSocket Secure. Default port for "ws" is 80, and for "wss" is 443.
            Dim hostDescriptor = New SparkplugHostDescriptor("ws://localhost:8080/mqtt")

            ' Instantiate the consumer object and hook events.
            Dim consumer = New EasySparkplugConsumer()
            AddHandler consumer.MetricNotification, AddressOf consumer_WebSocket_MetricNotification

            Console.WriteLine("Subscribing...")
            ' In this example, we specify the precise Sparkplug group ID and edge node ID, but allow any metric name.
            consumer.SubscribeEdgeNodeMetric(hostDescriptor,
                "easyGroup", "easySparkplugDemo", "#")

            Console.WriteLine("Processing notifications for 20 seconds...")
            Threading.Thread.Sleep(20 * 1000)

            Console.WriteLine("Unsubscribing...")
            consumer.UnsubscribeAllMetrics()

            Console.WriteLine("Waiting for 5 seconds...")
            Threading.Thread.Sleep(5 * 1000)

            Console.WriteLine("Finished.")
        End Sub

        Private Shared Sub consumer_WebSocket_MetricNotification(ByVal sender As Object, ByVal eventArgs As EasySparkplugMetricNotificationEventArgs)
            ' Handle different types of notifications.
            Console.WriteLine()
            Select Case eventArgs.NotificationType
                Case SparkplugNotificationType.Connect
                    Console.WriteLine($"Connected to Sparkplug host, client ID: {eventArgs.ClientId}.")
                Case SparkplugNotificationType.Disconnect
                    Console.WriteLine("Disconnected from Sparkplug host.")
                Case SparkplugNotificationType.Data
                    Console.WriteLine("Received data from Sparkplug host.")
                    Console.WriteLine($"Metric name: {eventArgs.MetricName}")
                    Console.WriteLine($"Value: {eventArgs.MetricData?.Value}")
                Case SparkplugNotificationType.Birth
                    Console.WriteLine("Received birth message from Sparkplug host.")
                    Console.WriteLine($"Metric name: {eventArgs.MetricName}")
                    Console.WriteLine($"Value: {eventArgs.MetricData?.Value}")
                Case SparkplugNotificationType.Death
                    Console.WriteLine("Received death message from Sparkplug host.")
                    Console.WriteLine($"Metric name: {eventArgs.MetricName}")
            End Select
            If Not eventArgs.Succeeded Then
                Console.WriteLine($"*** Failure: {eventArgs.ErrorMessageBrief}")
            End If
        End Sub
    End Class
End Namespace

 

Example (Edge Node)

.NET

// This example shows how to create a Sparkplug edge node with a single metric, start and stop it, using WebSocket.
//
// You can use any Sparkplug application, including our SparkplugCmd utility and the SparkplugApplicationConsoleDemo
// program, to subscribe to the edge node data. 
// The MQTT broker may need additional configuration to support WebSocket connections, such as enabling the WebSocket port
// and setting up the path.
//
// Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-ConnectivityStudio/Latest/examples.html .
// Sparkplug examples in C# on GitHub: https://github.com/OPCLabs/Examples-ConnectivityStudio-CSharp .
// Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
// a commercial license in order to use Online Forums, and we reply to every post.

using System;
using OpcLabs.EasySparkplug;
using OpcLabs.EasySparkplug.OperationModel;

namespace SparkplugDocExamples.EdgeNode._EasySparkplugEdgeNode
{
    partial class Start_Stop
    {
        static public void WebSocket()
        {
            // The WebSocket protocol can be specified in the broker URL using the "ws" scheme, as below.
            // Note: Use the "wss" scheme for WebSocket Secure. Default port for "ws" is 80, and for "wss" is 443.
            var hostDescriptor = new SparkplugHostDescriptor("ws://localhost:8080/mqtt");

            // Instantiate the edge node object and hook events.
            var edgeNode = new EasySparkplugEdgeNode(hostDescriptor,
                "easyGroup", "easySparkplugDemo");
            edgeNode.SystemConnectionStateChanged += edgeNode_WebSocket_SystemConnectionStateChanged;

            // Define a metric providing random integers.
            var random = new Random();
            edgeNode.Metrics.Add(new SparkplugMetric("MyMetric").ReadValueFunction(() => random.Next()));

            // Start the edge node.
            Console.WriteLine("The edge node is starting...");
            edgeNode.Start();

            Console.WriteLine("The edge node is started.");
            Console.WriteLine();

            // Let the user decide when to stop.
            Console.WriteLine("Press Enter to stop the edge node...");
            Console.ReadLine();

            // Stop the edge node.
            Console.WriteLine("The edge node is stopping...");
            edgeNode.Stop();

            Console.WriteLine("The edge node is stopped.");
        }


        static void edgeNode_WebSocket_SystemConnectionStateChanged(
            object sender, 
            SparkplugConnectionStateChangedEventArgs eventArgs)
        {
            // Display the new connection state (such as when the connection to the broker succeeds or fails).
            Console.WriteLine($"{nameof(EasySparkplugEdgeNode.SystemConnectionStateChanged)}: {eventArgs}");
        }
    }
}
' This example shows how to create a Sparkplug edge node with a single metric, start and stop it, using WebSocket.
'
' You can use any Sparkplug application, including our SparkplugCmd utility and the SparkplugApplicationConsoleDemo
' program, to subscribe to the edge node data.
' The MQTT broker may need additional configuration to support WebSocket connections, such as enabling the WebSocket port
' and setting up the path.
'
' Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-ConnectivityStudio/Latest/examples.html .
' Sparkplug examples in C# on GitHub: https://github.com/OPCLabs/Examples-ConnectivityStudio-CSharp .
' Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
' a commercial license in order to use Online Forums, and we reply to every post.

Imports OpcLabs.EasySparkplug
Imports OpcLabs.EasySparkplug.OperationModel

Namespace Global.SparkplugDocExamples.EdgeNode._EasySparkplugEdgeNode
    Partial Class Start_Stop
        Public Shared Sub WebSocket()
            ' The WebSocket protocol can be specified in the broker URL using the "ws" scheme, as below.
            ' Note: Use the "wss" scheme for WebSocket Secure. Default port for "ws" is 80, and for "wss" is 443.
            Dim hostDescriptor = New SparkplugHostDescriptor("ws://localhost:8080/mqtt")

            ' Instantiate the edge node object and hook events.
            Dim edgeNode = New EasySparkplugEdgeNode(hostDescriptor,
                                                     "easyGroup", "easySparkplugDemo")
            AddHandler edgeNode.SystemConnectionStateChanged, AddressOf edgeNode_WebSocket_SystemConnectionStateChanged

            ' Define a metric providing random integers.
            Dim random = New Random()
            edgeNode.Metrics.Add(New SparkplugMetric("MyMetric").ReadValueFunction(Function() random.Next()))

            ' Start the edge node.
            Console.WriteLine("The edge node is starting...")
            edgeNode.Start()

            Console.WriteLine("The edge node is started.")
            Console.WriteLine()

            ' Let the user decide when to stop.
            Console.WriteLine("Press Enter to stop the edge node...")
            Console.ReadLine()

            ' Stop the edge node.
            Console.WriteLine("The edge node is stopping...")
            edgeNode.Stop()

            Console.WriteLine("The edge node is stopped.")
        End Sub

        Private Shared Sub edgeNode_WebSocket_SystemConnectionStateChanged _
            (ByVal sender As Object, ByVal eventArgs As SparkplugConnectionStateChangedEventArgs)
            ' Display the new connection state (such as when the connection to the broker succeeds or fails).
            Console.WriteLine($"{NameOf(EasySparkplugEdgeNode.SystemConnectionStateChanged)}: {eventArgs}")
        End Sub
    End Class
End Namespace

 

Specifying MQTT Client ID

MQTT uses the client ID (a string) to distinguish between the clients (in Sparkplug, host applications and edge nodes) that are connecting to the broker. The client ID must therefore be unique among all clients that connect to the same broker. Client ID can also be used for other purposes on the broker, such as diagnostics, or authorization (access control).

By default, the component generates a unique, semi-random client ID. The Sparkplug host application ID, or the edge node ID, is incorporated as a prefix in the auto-generated client ID.

If you need a specific MQTT client ID, you can set it in the connection descriptor, using the ClientId Property. When it is empty, the auto-generated client ID is used for the MQTT connections.

The following examples illustrate how to specify a custom MQTT client ID for your Sparkplug host application or edge node.

Example (Host Application)

.NET

// This example shows how to subscribe to all metrics of a given edge node, specifying an MQTT client ID.
//
// In order to publish or observe messages for this example, start the SparkplugEdgeNodeConsoleDemo program first.
//
// Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-ConnectivityStudio/Latest/examples.html .
// Sparkplug examples in C# on GitHub: https://github.com/OPCLabs/Examples-ConnectivityStudio-CSharp .
// Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
// a commercial license in order to use Online Forums, and we reply to every post.

using System;
using OpcLabs.EasySparkplug;
using OpcLabs.EasySparkplug.OperationModel;

namespace SparkplugDocExamples.Consumer._EasySparkplugConsumer
{
    partial class SubscribeEdgeNodeMetric
    {
        public static void ClientId()
        {
            // The MQTT client ID can be specified in the connection descriptor. When empty (the default), the component
            // generates a unique, semi-random client ID.
            // Note that the default port for the "mqtt" scheme is 1883.
            var hostDescriptor = new SparkplugHostDescriptor("mqtt://localhost")
            {
                ConnectionDescriptor =
                {
                    ClientId = "myApplication"
                }
            };

            // Alternatively, the MQTT client ID can be specified in the broker URL using the "clientId" query parameter,
            // as below.
            var hostDescriptor2 = new SparkplugHostDescriptor("mqtt://localhost?clientId=myApplication");

            // Instantiate the consumer object and hook events.
            var consumer = new EasySparkplugConsumer();
            consumer.MetricNotification += consumer_ClientId_MetricNotification;

            Console.WriteLine("Subscribing...");
            // In this example, we specify the precise Sparkplug group ID and edge node ID, but allow any metric name.
            consumer.SubscribeEdgeNodeMetric(hostDescriptor,    // or hostDescriptor2, if you prefer the alternative method
                "easyGroup", "easySparkplugDemo", "#");

            Console.WriteLine("Processing notifications for 20 seconds...");
            System.Threading.Thread.Sleep(20 * 1000);

            Console.WriteLine("Unsubscribing...");
            consumer.UnsubscribeAllMetrics();

            Console.WriteLine("Waiting for 5 seconds...");
            System.Threading.Thread.Sleep(5 * 1000);

            Console.WriteLine("Finished.");
        }


        static void consumer_ClientId_MetricNotification(object sender, EasySparkplugMetricNotificationEventArgs eventArgs)
        {
            // Handle different types of notifications.
            Console.WriteLine();
            switch (eventArgs.NotificationType)
            {
                case SparkplugNotificationType.Connect:
                    Console.WriteLine($"Connected to Sparkplug host, client ID: {eventArgs.ClientId}.");
                    break;
                case SparkplugNotificationType.Disconnect:
                    Console.WriteLine("Disconnected from Sparkplug host.");
                    break;
                case SparkplugNotificationType.Data:
                    Console.WriteLine("Received data from Sparkplug host.");
                    Console.WriteLine($"Metric name: {eventArgs.MetricName}");
                    Console.WriteLine($"Value: {eventArgs.MetricData?.Value}");
                    break;
                case SparkplugNotificationType.Birth:
                    Console.WriteLine("Received birth message from Sparkplug host.");
                    Console.WriteLine($"Metric name: {eventArgs.MetricName}");
                    Console.WriteLine($"Value: {eventArgs.MetricData?.Value}");
                    break;
                case SparkplugNotificationType.Death:
                    Console.WriteLine("Received death message from Sparkplug host.");
                    Console.WriteLine($"Metric name: {eventArgs.MetricName}");
                    break;
            }
            if (!eventArgs.Succeeded)
                Console.WriteLine($"*** Failure: {eventArgs.ErrorMessageBrief}");
        }
    }
}
' This example shows how to subscribe to all metrics of a given edge node, specifying an MQTT client ID.
'
' In order to publish or observe messages for this example, start the SparkplugEdgeNodeConsoleDemo program first.
'
' Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-ConnectivityStudio/Latest/examples.html .
' Sparkplug examples in C# on GitHub: https://github.com/OPCLabs/Examples-ConnectivityStudio-CSharp .
' Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
' a commercial license in order to use Online Forums, and we reply to every post.

Imports OpcLabs.EasySparkplug
Imports OpcLabs.EasySparkplug.OperationModel

Namespace Global.SparkplugDocExamples.Consumer._EasySparkplugConsumer
    Partial Class SubscribeEdgeNodeMetric
        Public Shared Sub ClientId()
            ' The MQTT client ID can be specified in the connection descriptor. When empty (the default), the component
            ' generates a unique, semi-random client ID.
            ' Note that the default port for the "mqtt" scheme is 1883.
            Dim hostDescriptor = New SparkplugHostDescriptor("mqtt://localhost")
            hostDescriptor.ConnectionDescriptor.ClientId = "myApplication"

            ' Alternatively, the MQTT client ID can be specified in the broker URL using the "clientId" query parameter,
            ' as below.
            Dim hostDescriptor2 = New SparkplugHostDescriptor("mqtt://localhost?clientId=myApplication")

            ' Instantiate the consumer object and hook events.
            Dim consumer = New EasySparkplugConsumer()
            AddHandler consumer.MetricNotification, AddressOf consumer_ClientId_MetricNotification

            Console.WriteLine("Subscribing...")
            ' In this example, we specify the precise Sparkplug group ID and edge node ID, but allow any metric name.
            consumer.SubscribeEdgeNodeMetric(hostDescriptor, ' or hostDescriptor2, if you prefer the alternative method
                "easyGroup", "easySparkplugDemo", "#")

            Console.WriteLine("Processing notifications for 20 seconds...")
            Threading.Thread.Sleep(20 * 1000)

            Console.WriteLine("Unsubscribing...")
            consumer.UnsubscribeAllMetrics()

            Console.WriteLine("Waiting for 5 seconds...")
            Threading.Thread.Sleep(5 * 1000)

            Console.WriteLine("Finished.")
        End Sub

        Private Shared Sub consumer_ClientId_MetricNotification(ByVal sender As Object, ByVal eventArgs As EasySparkplugMetricNotificationEventArgs)
            ' Handle different types of notifications.
            Console.WriteLine()
            Select Case eventArgs.NotificationType
                Case SparkplugNotificationType.Connect
                    Console.WriteLine($"Connected to Sparkplug host, client ID: {eventArgs.ClientId}.")
                Case SparkplugNotificationType.Disconnect
                    Console.WriteLine("Disconnected from Sparkplug host.")
                Case SparkplugNotificationType.Data
                    Console.WriteLine("Received data from Sparkplug host.")
                    Console.WriteLine($"Metric name: {eventArgs.MetricName}")
                    Console.WriteLine($"Value: {eventArgs.MetricData?.Value}")
                Case SparkplugNotificationType.Birth
                    Console.WriteLine("Received birth message from Sparkplug host.")
                    Console.WriteLine($"Metric name: {eventArgs.MetricName}")
                    Console.WriteLine($"Value: {eventArgs.MetricData?.Value}")
                Case SparkplugNotificationType.Death
                    Console.WriteLine("Received death message from Sparkplug host.")
                    Console.WriteLine($"Metric name: {eventArgs.MetricName}")
            End Select
            If Not eventArgs.Succeeded Then
                Console.WriteLine($"*** Failure: {eventArgs.ErrorMessageBrief}")
            End If
        End Sub
    End Class
End Namespace

 

Example (Edge Node)

.NET

// This example shows how to create a Sparkplug edge node with a single metric, start and stop it, specifying an MQTT
// client ID.
//
// You can use any Sparkplug application, including our SparkplugCmd utility and the SparkplugApplicationConsoleDemo
// program, to subscribe to the edge node data. 
//
// Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-ConnectivityStudio/Latest/examples.html .
// Sparkplug examples in C# on GitHub: https://github.com/OPCLabs/Examples-ConnectivityStudio-CSharp .
// Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
// a commercial license in order to use Online Forums, and we reply to every post.

using System;
using OpcLabs.EasySparkplug;
using OpcLabs.EasySparkplug.OperationModel;

namespace SparkplugDocExamples.EdgeNode._EasySparkplugEdgeNode
{
    partial class Start_Stop
    {
        static public void ClientId()
        {
            // The MQTT client ID can be specified in the connection descriptor. When empty (the default), the component
            // generates a unique, semi-random client ID.
            // Note that the default port for the "mqtt" scheme is 1883.
            var hostDescriptor = new SparkplugHostDescriptor("mqtt://localhost")
            {
                ConnectionDescriptor =
                {
                    ClientId = "myApplication"
                }
            };

            // Alternatively, the MQTT client ID can be specified in the broker URL using the "clientId" query parameter,
            // as below.
            var hostDescriptor2 = new SparkplugHostDescriptor("mqtt://localhost?clientId=myApplication");

            // Instantiate the edge node object and hook events.
            var edgeNode = new EasySparkplugEdgeNode(hostDescriptor,    // or hostDescriptor2, if you prefer the alternative method
                "easyGroup", "easySparkplugDemo");
            edgeNode.SystemConnectionStateChanged += edgeNode_ClientId_SystemConnectionStateChanged;

            // Define a metric providing random integers.
            var random = new Random();
            edgeNode.Metrics.Add(new SparkplugMetric("MyMetric").ReadValueFunction(() => random.Next()));

            // Start the edge node.
            Console.WriteLine("The edge node is starting...");
            edgeNode.Start();

            Console.WriteLine("The edge node is started.");
            Console.WriteLine();

            // Let the user decide when to stop.
            Console.WriteLine("Press Enter to stop the edge node...");
            Console.ReadLine();

            // Stop the edge node.
            Console.WriteLine("The edge node is stopping...");
            edgeNode.Stop();

            Console.WriteLine("The edge node is stopped.");
        }


        static void edgeNode_ClientId_SystemConnectionStateChanged(
            object sender, 
            SparkplugConnectionStateChangedEventArgs eventArgs)
        {
            // Display the new connection state (such as when the connection to the broker succeeds or fails).
            Console.WriteLine($"{nameof(EasySparkplugEdgeNode.SystemConnectionStateChanged)}: {eventArgs}");
        }
    }
}
' This example shows how to create a Sparkplug edge node with a single metric, start and stop it, specifying an MQTT
' client ID.
'
' You can use any Sparkplug application, including our SparkplugCmd utility and the SparkplugApplicationConsoleDemo
' program, to subscribe to the edge node data.
'
' Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-ConnectivityStudio/Latest/examples.html .
' Sparkplug examples in C# on GitHub: https://github.com/OPCLabs/Examples-ConnectivityStudio-CSharp .
' Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
' a commercial license in order to use Online Forums, and we reply to every post.

Imports OpcLabs.EasySparkplug
Imports OpcLabs.EasySparkplug.OperationModel

Namespace Global.SparkplugDocExamples.EdgeNode._EasySparkplugEdgeNode
    Partial Class Start_Stop
        Public Shared Sub ClientId()
            ' The MQTT client ID can be specified in the connection descriptor. When empty (the default), the component
            ' generates a unique, semi-random client ID.
            ' Note that the default port for the "mqtt" scheme is 1883.
            Dim hostDescriptor = New SparkplugHostDescriptor("mqtt://localhost")
            hostDescriptor.ConnectionDescriptor.ClientId = "myApplication"

            ' Alternatively, the MQTT client ID can be specified in the broker URL using the "clientId" query parameter,
            ' as below.
            Dim hostDescriptor2 = New SparkplugHostDescriptor("mqtt://localhost?clientId=myApplication")

            ' Instantiate the edge node object and hook events.
            Dim edgeNode = New EasySparkplugEdgeNode(hostDescriptor, ' or hostDescriptor2, if you prefer the alternative method
                                                     "easyGroup", "easySparkplugDemo")
            AddHandler edgeNode.SystemConnectionStateChanged, AddressOf edgeNode_ClientId_SystemConnectionStateChanged

            ' Define a metric providing random integers.
            Dim random = New Random()
            edgeNode.Metrics.Add(New SparkplugMetric("MyMetric").ReadValueFunction(Function() random.Next()))

            ' Start the edge node.
            Console.WriteLine("The edge node is starting...")
            edgeNode.Start()

            Console.WriteLine("The edge node is started.")
            Console.WriteLine()

            ' Let the user decide when to stop.
            Console.WriteLine("Press Enter to stop the edge node...")
            Console.ReadLine()

            ' Stop the edge node.
            Console.WriteLine("The edge node is stopping...")
            edgeNode.Stop()

            Console.WriteLine("The edge node is stopped.")
        End Sub

        Private Shared Sub edgeNode_ClientId_SystemConnectionStateChanged _
            (ByVal sender As Object, ByVal eventArgs As SparkplugConnectionStateChangedEventArgs)
            ' Display the new connection state (such as when the connection to the broker succeeds or fails).
            Console.WriteLine($"{NameOf(EasySparkplugEdgeNode.SystemConnectionStateChanged)}: {eventArgs}")
        End Sub
    End Class
End Namespace

 

Configuring Connection Parameters

The connection to the MQTT broker (system connection) has various parameters that can be configured. Rapid Toolkit for Sparkplug provides reasonable defaults. These parameters include:

When developing Sparkplug host applications, the system connection parameters are accessible through the EasySparkplugHostApplication Class. When developing Sparkplug edge nodes, the system connection parameters are accessible on the EasySparkplugEdgeNode Class.

The following examples illustrate how to configure the system connection parameters in Sparkplug host applications and edge nodes.

Example (Host Application)

.NET

// This example shows how to configure connection parameters of the Sparkplug host application.
//
// In order to publish or observe messages for this example, start the SparkplugEdgeNodeConsoleDemo program first.
//
// Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-ConnectivityStudio/Latest/examples.html .
// Sparkplug examples in C# on GitHub: https://github.com/OPCLabs/Examples-ConnectivityStudio-CSharp .
// Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
// a commercial license in order to use Online Forums, and we reply to every post.

using System;
using System.Collections.Generic;
using OpcLabs.EasySparkplug;
using OpcLabs.EasySparkplug.OperationModel;
using OpcLabs.EasySparkplug.System;

namespace SparkplugDocExamples.Consumer._EasySparkplugHostApplication
{
    class SystemConnectionParameters
    {
        public static void Main1()
        {
            // Note that the default port for the "mqtt" scheme is 1883.
            var hostDescriptor = new SparkplugHostDescriptor("mqtt://localhost");

            // Pre-create the host application, so that we can configure it.
            EasySparkplugHostApplication hostApplication = EasySparkplugInfrastructure.Instance.FindOrCreateHostApplication(hostDescriptor);
            
            // Configure various connection parameters of the host application.
            hostApplication.SystemConnectionParameters.MqttKeepAliveInterval = 2 * 1000; // 2 seconds
            hostApplication.SystemConnectionParameters.MqttKeepAliveIntervalDebug = 2 * 1000; // 2 seconds
            hostApplication.SystemConnectionParameters.PublishConnectionTimeout = 10 * 1000;   // 10 seconds
            hostApplication.SystemConnectionParameters.ReconnectInterval = 5 * 1000; // 5 seconds

            // Instantiate the consumer object.
            var consumer = new EasySparkplugConsumer();

            Console.WriteLine("Subscribing...");
            // Thanks to implicit conversion, EasySparkplugHostApplication can be used in place of SparkplugHostDescriptor.
            consumer.SubscribeEdgeNodePayload(hostApplication, "easyGroup", "easySparkplugDemo",
                (sender, eventArgs) =>
                {
                    // Handle different types of notifications.
                    Console.WriteLine();
                    switch (eventArgs.NotificationType)
                    {
                        case SparkplugNotificationType.Connect:
                            Console.WriteLine($"Connected to Sparkplug host, client ID: {eventArgs.ClientId}.");
                            break;
                        case SparkplugNotificationType.Disconnect:
                            Console.WriteLine("Disconnected from Sparkplug host.");
                            break;
                        case SparkplugNotificationType.Data:
                        case SparkplugNotificationType.Birth:
                            Console.WriteLine("Received birth or data message from Sparkplug host.");
                            // Display the metrics name and data for each metric delivered in the payload.
                            foreach (KeyValuePair<string, SparkplugMetricElement> pair in eventArgs.Payload)
                                Console.WriteLine($"{pair.Key}: {pair.Value.MetricData}");
                            break;
                        case SparkplugNotificationType.Death:
                            Console.WriteLine("Received death message from Sparkplug host.");
                            break;
                    }
                    if (!eventArgs.Succeeded)
                        Console.WriteLine($"*** Failure: {eventArgs.ErrorMessageBrief}");
                });

            Console.WriteLine("Processing notifications for 60 seconds...");
            System.Threading.Thread.Sleep(60 * 1000);

            Console.WriteLine("Unsubscribing...");
            consumer.UnsubscribeAllPayloads();

            Console.WriteLine("Waiting for 5 seconds...");
            System.Threading.Thread.Sleep(5 * 1000);

            Console.WriteLine("Finished.");
        }
    }
}
' This example shows how to configure connection parameters of the Sparkplug host application.
'
' In order to publish or observe messages for this example, start the SparkplugEdgeNodeConsoleDemo program first.
'
' Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-ConnectivityStudio/Latest/examples.html .
' Sparkplug examples in C# on GitHub: https://github.com/OPCLabs/Examples-ConnectivityStudio-CSharp .
' Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
' a commercial license in order to use Online Forums, and we reply to every post.

Imports OpcLabs.EasySparkplug
Imports OpcLabs.EasySparkplug.OperationModel
Imports OpcLabs.EasySparkplug.System

Namespace Global.SparkplugDocExamples.Consumer._EasySparkplugHostApplication
    Class SystemConnectionParameters
        Public Shared Sub Main1()
            ' Note that the default port for the "mqtt" scheme is 1883.
            Dim hostDescriptor = New SparkplugHostDescriptor("mqtt://localhost")

            ' Pre-create the host application, so that we can control it.
            Dim hostApplication As EasySparkplugHostApplication = EasySparkplugInfrastructure.Instance.FindOrCreateHostApplication(hostDescriptor)

            ' Configure various connection parameters of the host application.
            hostApplication.SystemConnectionParameters.MqttKeepAliveInterval = 2 * 1000 ' 2 seconds
            hostApplication.SystemConnectionParameters.MqttKeepAliveIntervalDebug = 2 * 1000 ' 2 seconds
            hostApplication.SystemConnectionParameters.PublishConnectionTimeout = 10 * 1000 ' 10 seconds
            hostApplication.SystemConnectionParameters.ReconnectInterval = 5 * 1000 ' 5 seconds

            ' Instantiate the consumer object.
            Dim consumer = New EasySparkplugConsumer()

            Console.WriteLine("Subscribing...")
            ' Thanks to implicit conversion, EasySparkplugHostApplication can be used in place of SparkplugHostDescriptor.
            consumer.SubscribeEdgeNodePayload(hostApplication, "easyGroup", "easySparkplugDemo",
                Sub(sender, eventArgs)
                    ' Handle different types of notifications.
                    Console.WriteLine()
                    Select Case eventArgs.NotificationType
                        Case SparkplugNotificationType.Connect
                            Console.WriteLine($"Connected to Sparkplug host, client ID: {eventArgs.ClientId}.")
                        Case SparkplugNotificationType.Disconnect
                            Console.WriteLine("Disconnected from Sparkplug host.")
                        Case SparkplugNotificationType.Data,
                            SparkplugNotificationType.Birth
                            Console.WriteLine("Received birth or data message from Sparkplug host.")
                            ' Display the metrics name and data for each metric delivered in the payload.
                            For Each pair As KeyValuePair(Of String, SparkplugMetricElement) In eventArgs.Payload
                                Console.WriteLine($"{pair.Key}: {pair.Value.MetricData}")
                            Next
                        Case SparkplugNotificationType.Death
                            Console.WriteLine("Received death message from Sparkplug host.")
                    End Select
                    If Not eventArgs.Succeeded Then
                        Console.WriteLine($"*** Failure: {eventArgs.ErrorMessageBrief}")
                    End If
                End Sub)

            Console.WriteLine("Processing notifications for 60 seconds...")
            System.Threading.Thread.Sleep(60 * 1000)

            Console.WriteLine("Unsubscribing...")
            consumer.UnsubscribeAllPayloads()

            Console.WriteLine("Waiting for 5 seconds...")
            Threading.Thread.Sleep(5 * 1000)

            Console.WriteLine("Finished.")
        End Sub
    End Class
End Namespace

 

Example (Edge Node)

.NET

// This example shows how to configure connection parameters of the Sparkplug edge node.
//
// You can use any Sparkplug application, including our SparkplugCmd utility and the SparkplugApplicationConsoleDemo
// program, to subscribe to the edge node data. 
//
// Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-ConnectivityStudio/Latest/examples.html .
// Sparkplug examples in C# on GitHub: https://github.com/OPCLabs/Examples-ConnectivityStudio-CSharp .
// Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
// a commercial license in order to use Online Forums, and we reply to every post.

using System;
using OpcLabs.EasySparkplug;

namespace SparkplugDocExamples.EdgeNode._EasySparkplugEdgeNode
{
    class SystemConnectionParameters
    {
        static public void Main1()
        {
            // Note that the default port for the "mqtt" scheme is 1883.
            var hostDescriptor = new SparkplugHostDescriptor("mqtt://localhost");

            // Instantiate the edge node object and hook events.
            var edgeNode = new EasySparkplugEdgeNode(hostDescriptor, "easyGroup", "easySparkplugDemo");
            edgeNode.SystemConnectionStateChanged += (sender, eventArgs) =>
            {
                // Display the new connection state (such as when the connection to the broker succeeds or fails).
                Console.WriteLine($"{nameof(EasySparkplugEdgeNode.SystemConnectionStateChanged)}: {eventArgs}");
            };
            
            // Configure various connection parameters of the edge node.
            edgeNode.SystemConnectionParameters.MqttKeepAliveInterval = 2 * 1000; // 2 seconds
            edgeNode.SystemConnectionParameters.MqttKeepAliveIntervalDebug = 2 * 1000; // 2 seconds
            edgeNode.SystemConnectionParameters.PublishConnectionTimeout = 10 * 1000;   // 10 seconds
            edgeNode.SystemConnectionParameters.ReconnectInterval = 5 * 1000; // 5 seconds

            // Define a metric providing random integers.
            var random = new Random();
            edgeNode.Metrics.Add(new SparkplugMetric("MyMetric").ReadValueFunction(() => random.Next()));

            // Start the edge node.
            Console.WriteLine("The edge node is starting...");
            edgeNode.Start();

            Console.WriteLine("The edge node is started.");
            Console.WriteLine();

            // Let the user decide when to stop.
            Console.WriteLine("Press Enter to stop the edge node...");
            Console.ReadLine();

            // Stop the edge node.
            Console.WriteLine("The edge node is stopping...");
            edgeNode.Stop();

            Console.WriteLine("The edge node is stopped.");
        }
    }
}
' This example shows how to configure connection parameters of the Sparkplug edge node.
'
' You can use any Sparkplug application, including our SparkplugCmd utility and the SparkplugApplicationConsoleDemo
' program, to subscribe to the edge node data.
'
' Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-ConnectivityStudio/Latest/examples.html .
' Sparkplug examples in C# on GitHub: https://github.com/OPCLabs/Examples-ConnectivityStudio-CSharp .
' Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
' a commercial license in order to use Online Forums, and we reply to every post.

Imports OpcLabs.EasySparkplug

Namespace Global.SparkplugDocExamples.EdgeNode._EasySparkplugEdgeNode
    Class SystemConnectionParameters
        Public Shared Sub Main1()
            ' Note that the default port for the "mqtt" scheme is 1883.
            Dim hostDescriptor = New SparkplugHostDescriptor("mqtt://localhost")

            ' Instantiate the edge node object and hook events.
            Dim edgeNode = New EasySparkplugEdgeNode(hostDescriptor, "easyGroup", "easySparkplugDemo")
            AddHandler edgeNode.SystemConnectionStateChanged,
                Sub(sender, eventArgs)
                    ' Display the new connection state (such as when the connection to the broker succeeds or fails).
                    Console.WriteLine($"{NameOf(EasySparkplugEdgeNode.SystemConnectionStateChanged)}: {eventArgs}")
                End Sub

            ' Configure various connection parameters of the edge node.
            edgeNode.SystemConnectionParameters.MqttKeepAliveInterval = 2 * 1000 ' 2 seconds
            edgeNode.SystemConnectionParameters.MqttKeepAliveIntervalDebug = 2 * 1000 ' 2 seconds
            edgeNode.SystemConnectionParameters.PublishConnectionTimeout = 10 * 1000 ' 10 seconds
            edgeNode.SystemConnectionParameters.ReconnectInterval = 5 * 1000 ' 5 seconds

            ' Define a metric providing random integers.
            Dim random = New Random()
            edgeNode.Metrics.Add(New SparkplugMetric("MyMetric").ReadValueFunction(Function() random.Next()))

            ' Start the edge node.
            Console.WriteLine("The edge node is starting...")
            edgeNode.Start()

            Console.WriteLine("The edge node is started.")
            Console.WriteLine()

            ' Let the user decide when to stop.
            Console.WriteLine("Press Enter to stop the edge node...")
            Console.ReadLine()

            ' Stop the edge node.
            Console.WriteLine("The edge node is stopping...")
            edgeNode.Stop()

            Console.WriteLine("The edge node is stopped.")
        End Sub
    End Class
End Namespace

 

Connecting and Disconnecting Manually

Normally, Rapid Toolkit for Sparkplug takes care of connecting to and disconnecting from the Sparkplug system (MQTT broker). It also attempts to reconnect periodically in case of unwanted interruptions.

For Sparkplug host applications, Rapid Toolkit for Sparkplug connects to the MQTT broker whenever there is a subscription to metrics published to the broker, or metrics (Sparkplug commands) need to be published to the broker.

For Sparkplug edge nodes, this means that Rapid Toolkit for Sparkplug attempts to connect to the MQTT broker when the edge node starts, and it disconnects when the edge node stops. You can set the AutoConnectSystem Property on the edge node object to false, and then call the PerformConnectSystem Method to instruct the edge node to connect to the Sparkplug system, and the PerformDisconnectSystem Method to instruct the edge node to disconnect from the Sparkplug system. This is illustrated in the following example.

Example (Edge Node)

.NET

// This example shows how to connect to and disconnect from a Sparkplug system manually, without automatic connection on
// start.
//
// You can use any Sparkplug application, including our SparkplugCmd utility and the SparkplugApplicationConsoleDemo
// program, to subscribe to the edge node data. 
//
// Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-ConnectivityStudio/Latest/examples.html .
// Sparkplug examples in C# on GitHub: https://github.com/OPCLabs/Examples-ConnectivityStudio-CSharp .
// Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
// a commercial license in order to use Online Forums, and we reply to every post.

using System;
using OpcLabs.EasySparkplug;

namespace SparkplugDocExamples.EdgeNode._EasySparkplugEdgeNode
{
     class AutoConnectSystem
    {
        static public void Main1()
        {
            // Note that the default port for the "mqtt" scheme is 1883.
            var hostDescriptor = new SparkplugHostDescriptor("mqtt://localhost");

            // Instantiate the edge node object.
            var edgeNode = new EasySparkplugEdgeNode(hostDescriptor, "easyGroup", "easySparkplugDemo");

            // Configure the edge node so that we will connect to and disconnect from the Sparkplug system manually.
            edgeNode.AutoConnectSystem = false;
            
            // Hook the SystemConnectionStateChanged event to handle system connection state changes.
            edgeNode.SystemConnectionStateChanged += (sender, eventArgs) =>
            {
                // Display the new connection state (such as when the connection to the broker succeeds or fails).
                Console.WriteLine($"{nameof(EasySparkplugEdgeNode.SystemConnectionStateChanged)}: {eventArgs}");
            };

            // Hook the PublishingError event to handle errors that occur during publishing.
            edgeNode.PublishingError += (sender, eventArgs) =>
            {
                // Display the error that occurred.
                Console.WriteLine($"{nameof(EasySparkplugEdgeNode.PublishingError)}: {eventArgs}");
            };

            // Define a metric providing random integers.
            var random = new Random();
            edgeNode.Metrics.Add(new SparkplugMetric("MyMetric").ReadValueFunction(() => random.Next()));

            // Start the edge node.
            Console.WriteLine("The edge node is starting...");
            edgeNode.Start();

            // Obviously, since the edge node is already started and the data collection (polling) is used, there will be
            // publishing errors at this point, until we instruct the edge node to connect to the Sparkplug system.

            Console.WriteLine("The edge node is started.");
            Console.WriteLine();

            // Let the user decide when to connect.
            Console.WriteLine("Press Enter to connect...");
            Console.ReadLine();
            edgeNode.PerformConnectSystem();

            // The publishing errors will stop here (if the connection to the broker can be made), and the edge node will
            // start publishing data.

            // Let the user decide when to disconnect.
            Console.WriteLine("Press Enter to disconnect...");
            Console.ReadLine();
            edgeNode.PerformDisconnectSystem();

            // The publishing errors will resume here.

            // Let the user decide when to stop.
            Console.WriteLine("Press Enter to stop the edge node...");
            Console.ReadLine();

            // Stop the edge node.
            Console.WriteLine("The edge node is stopping...");
            edgeNode.Stop();

            Console.WriteLine("The edge node is stopped.");
        }
    }
}
' This example shows how to connect to and disconnect from a Sparkplug system manually, without automatic connection on
' start.
'
' You can use any Sparkplug application, including our SparkplugCmd utility and the SparkplugApplicationConsoleDemo
' program, to subscribe to the edge node data.
'
' Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-ConnectivityStudio/Latest/examples.html .
' Sparkplug examples in C# on GitHub: https://github.com/OPCLabs/Examples-ConnectivityStudio-CSharp .
' Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
' a commercial license in order to use Online Forums, and we reply to every post.

Imports OpcLabs.EasySparkplug

Namespace Global.SparkplugDocExamples.EdgeNode._EasySparkplugEdgeNode
    Class AutoConnectSystem
        Public Shared Sub Main1()
            ' Note that the default port for the "mqtt" scheme is 1883.
            Dim hostDescriptor = New SparkplugHostDescriptor("mqtt://localhost")

            ' Instantiate the edge node object.
            Dim edgeNode = New EasySparkplugEdgeNode(hostDescriptor, "easyGroup", "easySparkplugDemo")

            ' Configure the edge node so that we will connect to and disconnect from the Sparkplug system manually.
            edgeNode.AutoConnectSystem = False

            ' Hook the SystemConnectionStateChanged event to handle system connection state changes.
            AddHandler edgeNode.SystemConnectionStateChanged,
                Sub(sender, eventArgs)
                    ' Display the New connection state (such as when the connection to the broker succeeds Or fails).
                    Console.WriteLine($"{NameOf(EasySparkplugEdgeNode.SystemConnectionStateChanged)}: {eventArgs}")
                End Sub

            ' Hook the PublishingError event to handle errors that occur during publishing.
            AddHandler edgeNode.PublishingError,
                Sub(sender, eventArgs)
                    ' Display the error that occurred.
                    Console.WriteLine($"{NameOf(EasySparkplugEdgeNode.PublishingError)}: {eventArgs}")
                End Sub



            ' Define a metric providing random integers.
            Dim random = New Random()
            edgeNode.Metrics.Add(New SparkplugMetric("MyMetric").ReadValueFunction(Function() random.Next()))

            ' Start the edge node.
            Console.WriteLine("The edge node is starting...")
            edgeNode.Start()

            ' Obviously, since the edge node is already started and the data collection (polling) is used, there will be
            ' publishing errors at this point, until we instruct the edge node to connect to the Sparkplug system.

            Console.WriteLine("The edge node is started.")
            Console.WriteLine()

            ' Let the user decide when to connect.
            Console.WriteLine("Press Enter to connect...")
            Console.ReadLine()
            edgeNode.PerformConnectSystem()

            ' The publishing errors will stop here (if the connection to the broker can be made), and the edge node will
            ' start publishing data.

            ' Let the user decide when to disconnect.
            Console.WriteLine("Press Enter to disconnect...")
            Console.ReadLine()
            edgeNode.PerformDisconnectSystem()

            ' The publishing errors will resume here.

            ' Let the user decide when to stop.
            Console.WriteLine("Press Enter to stop the edge node...")
            Console.ReadLine()

            ' Stop the edge node.
            Console.WriteLine("The edge node is stopping...")
            edgeNode.Stop()

            Console.WriteLine("The edge node is stopped.")

        End Sub
    End Class
End Namespace

 

Advanced Topics

For more information, see

 

Sparkplug is a trademark of Eclipse Foundation, Inc. "MQTT" is a trademark of the OASIS Open standards consortium. Other related terms are trademarks of their respective owners. Any use of these terms on this site is for descriptive purposes only and does not imply any sponsorship, endorsement or affiliation.

See Also